<template>
  <div>
    <el-table :data="tableData" style="width: 100%" height="400px">
      <el-table-column prop="name" label="任务名称" width="150" fixed="left" />
      <el-table-column prop="role" label="角色" width="150" fixed="left" />
      <el-table-column v-for="day in days" :width="60">
        <template #header>
          <div>周{{ day.week }}</div>
          <div>{{ day.date.slice(5) }}</div>
        </template>
        <template #default="{ row }">
          <div :style="{ height: (row.height + 1) * 30 + 'px' }">
            <template v-for="item in row.child">
              <!-- <div
              :class="{
                start: day == item.start,
                end: day == item.end,
                isShow: isTaskInDay(item, day),
              }"
              style="height: 20px; margin: 10px 0"
            ></div> -->

              <div
                :class="{
                  start: day.date == item.start,
                  end: day.date == item.end,
                }"
                v-if="isTaskInDay(item, day.date)"
                :style="{
                  height: '20px',
                  width: '100%',
                  marginTop: item.top * 20 + item.top * 10 + 'px',
                  backgroundColor: '#409eff',
                  position: 'absolute',
                  top: 0,
                }"
              >
                {{ item.top }}
              </div>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";

// 假设只显示一周
const days = ref([]);

const tableData = ref([
  {
    name: "任务A",
    role: "角色A",
    child: [
      {
        start: "2025-07-20",
        end: "2025-07-23",
      },
      {
        start: "2025-07-21",
        end: "2025-07-22",
      },
      {
        start: "2025-07-24",
        end: "2025-07-29",
      },
      {
        start: "2025-08-01",
        end: "2025-08-02",
      },
    ],
  },
  {
    name: "任务B",
    role: "角色B",
    child: [
      { start: "2025-07-24", end: "2025-07-26" },
      { start: "2025-07-25", end: "2025-07-28" },
      { start: "2025-07-24", end: "2025-07-26" },
    ],
  },
  {
    name: "任务C",
    role: "角色C",
    child: [
      { start: "2025-07-27", end: "2025-07-29" },
      { start: "2025-07-27", end: "2025-07-29" },
      { start: "2025-07-27", end: "2025-07-29" },
    ],
  },
]);

function isTaskInDay(row, day) {
  return (
    new Date(day) >= new Date(row.start) && new Date(day) <= new Date(row.end)
  );
}

/**
 * 获取开始日期到结束日期之间的所有天数及星期几
 * @param {string|Date} start 开始日期（如'2023-01-01'或Date对象）
 * @param {string|Date} end 结束日期（如'2023-01-05'或Date对象）
 * @returns {Array<{date: string, week: string}>} 每天的日期和星期几
 */
const getDaysWithWeek = (start, end) => {
  const weekMap = ["日", "一", "二", "三", "四", "五", "六"];
  const startDate = new Date(start);
  const endDate = new Date(end);
  const days = [];

  if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
    throw new Error(
      "无效的日期格式，请使用正确的日期字符串（如YYYY-MM-DD）或Date对象"
    );
  }
  if (startDate > endDate) {
    throw new Error("开始日期不能晚于结束日期");
  }

  let currentDate = new Date(startDate);
  while (currentDate <= endDate) {
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, "0");
    const day = String(currentDate.getDate()).padStart(2, "0");
    const week = weekMap[currentDate.getDay()];
    days.push({
      date: `${year}-${month}-${day}`,
      week,
    });
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return days;
};
/**
 * 判断两个日期区间是否重叠
 * @param {Date|string} start1 第一个区间的开始日期
 * @param {Date|string} end1 第一个区间的结束日期
 * @param {Date|string} start2 第二个区间的开始日期
 * @param {Date|string} end2 第二个区间的结束日期
 * @returns {boolean} 如果重叠返回true，否则返回false
 */
const isDateRangeOverlapping = (start1, end1, array) => {
  // 将输入转换为Date对象
  const s1 = new Date(start1);
  const e1 = new Date(end1);

  // 判断重叠条件
  let mumber = 0;
  array.forEach((element) => {
    const start = new Date(element.start);
    const end = new Date(element.end);
    if (e1 >= start && end >= s1) {
      mumber++;
    }
  });
  return mumber;
};

onMounted(() => {
  days.value = getDaysWithWeek("2025-07-20", "2025-08-20");

  tableData.value.forEach((element) => {
    element.height = 0;
    // 把长度小的排在前面
    // element.child = element.child.sort((a, b) => {});
    element.child.forEach((item, index) => {
      item.top =
        isDateRangeOverlapping(
          item.start,
          item.end,
          element.child.slice(0, index + 1)
        ) - 1;
      element.height = item.top > element.height ? item.top : element.height;
    });
  });
  console.log(days);
});
const listData = [
  {
    label: "部门名称",
    id: "部门id",
    children: [
      {
        label: "员工姓名",
        id: "员工id",
        role: "角色",
        roleId: "角色id",
        children: [
          {
            workItem: "任务名称",
            id: "任务id",
            projectId: "项目id",
            levelLeaf: "工作项级别节点",
            startDate: "开始日期",
            completeDate: "完成日期",
            status: "状态",
            workProgress: "进度",
          },
        ],
      },
    ],
  },
];
</script>

<style scoped>
::v-deep .el-table .cell {
  padding: 0 !important;
  text-align: center;
  position: static;
}
::v-deep .el-table .el-table__cell {
  padding: 0 !important;
}

.start {
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}
.end {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}
.isShow {
  background-color: #409eff;
}
</style>
